import React from 'react'
import { Table } from 'antd'
import PropTypes from 'prop-types';
import styles from './LwjTable.less'

const LwjTable = ({
  dataSource,
  pagination,
  loading,
  columns,
  selectType,
  onSelectRows,
  dispatch,
  pageChangeAction,
  onRowClick,
  onRowMouseEnter,
  selectedRowKeys = [],
  ...extConfigs
}) => {

  /**
   * 分页onchange方法
   * @param page
   */
  const onChange = (page) => {
    dispatch({
      type: pageChangeAction,
      payload: {
        limit: page.pageSize,
        start: page.current - 1,
        isTablePagination: true
      }
    })
  };

  if (!onRowClick) {
    onRowClick = () => { }
  }

  if (!onRowMouseEnter) {
    onRowMouseEnter = () => { }
  }

  if (columns) {
    /**
     * 每一列可以使用align来指定排列样式,默认为居中
     * 参数 (left|right)
     */
    columns.map((col) => {
      if (col.align === "left") {
        col.className = styles.alignLeft;
      } else if (col.align === "right") {
        col.className = styles.alignRight;
      } else if (col.align === "center") {
        col.className = styles.alignCenter;
      } else {
        col.className = styles.alignCenter;
      }
    })
  }
  /**
   * selectType参数用来指定列表单选或者多选
   * 参数：(multiple|single)
   */
  let TableProps = {};
  let rowSelection = {};
  if (selectType === 'multiple') {
    rowSelection = {
      type: 'check',
      onChange: onSelectRows,
      selectedRowKeys: selectedRowKeys
    }
  } else if (selectType === 'single') {
    rowSelection = {
      type: 'radio',
      onChange: onSelectRows,
      selectedRowKeys: selectedRowKeys
    }
  }


  let isRowSelectionNotNull = Object.keys(rowSelection).length !== 0;
  TableProps = { ...extConfigs };
  if (isRowSelectionNotNull) {
    TableProps.rowSelection = rowSelection;
  }
  return (
    <Table
      {...TableProps}
      onRow={(record) => {
        return {
          onClick: () => { onRowClick(record) },       // 点击行
          onMouseEnter: () => { onRowMouseEnter(record) },  // 鼠标移入行
        };
      }}
      dataSource={dataSource}
      pagination={pagination}
      onChange={onChange}
      loading={loading}
      className={styles.table}
      columns={columns}
      size="small"
      rowKey={record => record.id} />
  )
};

LwjTable.propTypes = {
  dataSource: PropTypes.array,
  pagination: PropTypes.any,
  loading: PropTypes.bool,
  columns: PropTypes.array,
  selectType: PropTypes.string,
  onSelectRows: PropTypes.func,
  dispatch: PropTypes.func,
  pageChangeAction: PropTypes.string,
  onRowClick: PropTypes.func
};

export default LwjTable
